﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WHC.Hotel.Entity;
using WHC.Hotel.BLL;
using WHC.OrderWater.Commons;
using WHC.Security.Entity;

namespace WHC.Hotel.UI
{
    public partial class FrmStockDispatch : BaseForm
    {
        public FrmStockDispatch()
        {
            InitializeComponent();
        }

        private void InitDictItem()
        {
            this.txtInWareHouse.Items.Clear();
            this.txtInWareHouse.Items.AddRange(DictItemUtil.GetWareHouse(false));
            this.txtOutWareHouse.Items.Clear();
            this.txtOutWareHouse.Items.AddRange(DictItemUtil.GetWareHouse(false));

            this.txtSearchInWareHouse.Items.Clear();
            this.txtSearchInWareHouse.Items.AddRange(DictItemUtil.GetWareHouse(true));
            this.txtSearchOutWareHouse.Items.Clear();
            this.txtSearchOutWareHouse.Items.AddRange(DictItemUtil.GetWareHouse(true));

            this.txtCreator.Items.Clear();
            this.txtSearchOperator.Items.Clear();
            List<UserInfo> userList = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.User>.Instance.GetAll();
            foreach (UserInfo info in userList)
            {
                this.txtCreator.Items.Add(info.FullName);
                this.txtSearchOperator.Items.Add(info.FullName);
            }
            this.txtCreator.SelectedIndex = this.txtCreator.FindString(Portal.gc.LoginInfo.FullName);

            this.dtStart.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            this.dtEnd.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));

            this.txtHandNo.Text = BLLFactory<StockDispatch>.Instance.GetHandNumber();
        }
        
        private void FrmPurchase_Load(object sender, EventArgs e)
        {
            InitDictItem();

            this.winGridView1.ProgressBar = this.toolStripProgressBar1.ProgressBar;
            this.winGridView1.AppendedMenu = this.contextMenuStrip1;
            this.winGridView1.dataGridView1.RowEnter += new DataGridViewCellEventHandler(dataGridView1_RowEnter);

            this.winGridView2.ProgressBar = this.toolStripProgressBar1.ProgressBar;
            this.winGridView2.AppendedMenu = this.contextMenuStrip2;
            
            #region 添加别名解析
            this.winGridView2.AddColumnAlias("HandNo", "货单号");
            this.winGridView2.AddColumnAlias("ItemNo", "项目编号");
            this.winGridView2.AddColumnAlias("ItemName", "项目名称");
            this.winGridView2.AddColumnAlias("Unit", "单位");
            this.winGridView2.AddColumnAlias("Price", "单价");
            this.winGridView2.AddColumnAlias("Quantity", "数量");
            #endregion
        }

        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            BindDetail();
        }

        private void BindDetail()
        {
            DataGridViewRow row;
            for (int i = 0; i < winGridView1.dataGridView1.SelectedRows.Count; i++)
            {
                row = winGridView1.dataGridView1.SelectedRows[i];
                string headID = row.Cells["ID"].Value.ToString();
                if (!string.IsNullOrEmpty(headID))
                {
                    this.winGridView2.PrintTitle = Portal.gc.gAppUnit + " -- " + string.Format("调拨单[{0}]的货品列表", headID);
                    this.winGridView2.DisplayColumns = "HandNo,ItemNo,ItemName,Unit,Price,Quantity";

                    DataTable dt = BLLFactory<StockDispatchDetail>.Instance.GetDispatchDetailReportByID(Convert.ToInt32(headID));
                    this.winGridView2.DataSource = dt.DefaultView;
                }

                break;
            }
        }

        private void BinData()
        {
            this.winGridView1.DisplayColumns = "ID,HandNo,OutWareHouse,InWareHouse,Note,CreateDate,Creator";

            #region 添加别名解析
            this.winGridView1.AddColumnAlias("ID", "编号");
            this.winGridView1.AddColumnAlias("HandNo", "货单编号");
            this.winGridView1.AddColumnAlias("CreateDate", "日期");
            this.winGridView1.AddColumnAlias("OutWareHouse", "调出仓库");
            this.winGridView1.AddColumnAlias("InWareHouse", "调入仓库");
            this.winGridView1.AddColumnAlias("Creator", "经手员工");
            this.winGridView1.AddColumnAlias("Note", "备注信息");
            #endregion

            SearchCondition condition = new SearchCondition();
            condition.AddCondition("CreateDate", this.dtStart.Value.ToString(), SqlOperator.MoreThanOrEqual)
                .AddCondition("CreateDate", this.dtEnd.Value.ToString(), SqlOperator.LessThanOrEqual)
                .AddCondition("Creator", this.txtSearchOperator.Text, SqlOperator.Like)
                .AddCondition("OutWareHouse", this.txtSearchOutWareHouse.Text.Replace("所有仓库",""), SqlOperator.Like)
                .AddCondition("InWareHouse", this.txtSearchInWareHouse.Text.Replace("所有仓库",""), SqlOperator.Like);
            string filter = condition.BuildConditionSql(DatabaseType.SqlServer);

            DataTable dt = BLLFactory<StockDispatch>.Instance.GetDispatchReport(filter);
            this.winGridView1.DataSource = dt.DefaultView;
            this.winGridView1.PrintTitle = Portal.gc.gAppUnit + " -- " + "库存调拨查询报表";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.txtInWareHouse.Text == "")
            {
                MessageUtil.ShowTips("请选择仓库");
                return;
            }

            FrmAddPurchaseGoods dlg = new FrmAddPurchaseGoods();
            dlg.WareHourse = this.txtOutWareHouse.Text;
            dlg.HandNumber = this.txtHandNo.Text;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                int i = 1;
                foreach (PurchaseDetailInfo info in dlg.detailDict.Values)
                {
                    ListViewItem item = new ListViewItem(info.ItemNo);
                    item.SubItems.Add(info.ItemName);
                    item.SubItems.Add(info.Unit);
                    item.SubItems.Add(info.Price.ToString("C2"));
                    item.SubItems.Add(info.Quantity.ToString());
                    item.SubItems.Add(info.Amount.ToString("C2"));
                    item.Tag = info;

                    this.lvwDetail.Items.Add(item);
                    i++;
                }
                CaculateMoney();
            }
        }

        private void CaculateMoney()
        {
            decimal allMoney = 0M;
            for (int i = 0; i < this.lvwDetail.Items.Count; i++)
            {
                PurchaseDetailInfo info = this.lvwDetail.Items[i].Tag as PurchaseDetailInfo;
                if (info != null)
                {
                    allMoney += info.Amount;
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.lvwDetail.SelectedItems.Count == 0) return;
            for (int i = this.lvwDetail.SelectedItems.Count - 1; i >= 0; i--)
            {
                this.lvwDetail.Items.RemoveAt(i);
            }
            CaculateMoney();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            #region 验证输入
            if (this.txtHandNo.Text.Trim() == "")
            {
                MessageUtil.ShowTips("货单编号不能为空");
                this.txtHandNo.Focus();
                return;
            }
            else if (this.txtOutWareHouse.Text.Trim() == "")
            {
                MessageUtil.ShowTips("请选择调出仓库");
                this.txtInWareHouse.Focus();
                return;
            }
            else if (this.txtInWareHouse.Text.Trim() == "")
            {
                MessageUtil.ShowTips("请选择调入仓库");
                this.txtInWareHouse.Focus();
                return;
            }
            else if (this.lvwDetail.Items.Count == 0)
            {
                MessageUtil.ShowTips("请添加商品");
                return;
            }
            else if (this.txtCreator.Text.Length == 0)
            {
                MessageUtil.ShowTips("请选择经手人");
                return;
            }
            #endregion

            try
            {
                StockDispatchInfo dispatchInfo = new StockDispatchInfo();
                dispatchInfo.CreateDate = this.txtCreateDate.Value;
                dispatchInfo.Creator = this.txtCreator.Text;
                dispatchInfo.HandNo = this.txtHandNo.Text;
                dispatchInfo.Note = this.txtNote.Text;
                dispatchInfo.InWareHouse = this.txtInWareHouse.Text;
                dispatchInfo.OutWareHouse = this.txtOutWareHouse.Text;

                int headId = BLLFactory<StockDispatch>.Instance.Insert2(dispatchInfo);
                if (headId > 0)
                {
                    for (int i = 0; i < this.lvwDetail.Items.Count; i++)
                    {
                        PurchaseDetailInfo detailInfo = this.lvwDetail.Items[i].Tag as PurchaseDetailInfo;
                        StockDispatchDetailInfo dispatchDetailInfo = new StockDispatchDetailInfo();
                        dispatchDetailInfo.ItemName = detailInfo.ItemName;
                        dispatchDetailInfo.ItemNo = detailInfo.ItemNo;
                        dispatchDetailInfo.Price = detailInfo.Price;
                        dispatchDetailInfo.Quantity = detailInfo.Quantity;
                        dispatchDetailInfo.Unit = detailInfo.Unit;                        
                        dispatchDetailInfo.StorageDispatch_ID = headId;

                        //记录单据，并增减库存
                        BLLFactory<StockDispatch>.Instance.DoStockDispatch(this.txtInWareHouse.Text,
                            this.txtOutWareHouse.Text, dispatchDetailInfo);
                    }

                    MessageUtil.ShowTips("保存成功");
                    ClearContent();
                }
                else
                {
                    MessageUtil.ShowError("保存失败");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                MessageUtil.ShowError(ex.Message);
            }
        }

        private void ClearContent()
        {
            this.txtHandNo.Text = BLLFactory<StockDispatch>.Instance.GetHandNumber();
            this.lvwDetail.Items.Clear();
            CaculateMoney();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            BinData();
        }

        private void menu_InRefresh_Click(object sender, EventArgs e)
        {
            CaculateMoney();
        }

        private void menu_Delete_Click(object sender, EventArgs e)
        {
            btnDelete_Click(null, null);
        }


        private void txtSearchWareHouse_SelectedIndexChanged(object sender, EventArgs e)
        {
            BinData();
        }

        private void menu_DetailRefresh_Click(object sender, EventArgs e)
        {

        }

        private void txtSearchInWareHouse_SelectedIndexChanged(object sender, EventArgs e)
        {
            BinData();
        }
    }
}
